package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.contact.GoodsManagerContact;
import com.xca.znb.entity.Goods;
import com.xca.znb.model.impl.GoodsManagerImpl;
import com.xca.znb.presenter.GoodsManagerPresenter;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

public class GoodsManager extends AppCompatActivity implements GoodsManagerContact {
    private GoodsManagerPresenter presenter ;
    private Button deleteBtn , updateBtn ;
    private ImageButton backBtn ;
    private ImageView titlePhoto ;
    private TextView goods_price , goods_unit , goods_state , goods_name ,
                     goods_local , goods_logistics , goods_details ;
    private ListView list_photo ;
    private ArrayList<String> imageList  = new ArrayList<>();
    private ArrayAdapter<String> adapter ;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_manager_activity);
        initView();

        GoodsManagerImpl goodsManager = new GoodsManagerImpl(this);
        presenter = new GoodsManagerPresenter(this,goodsManager);

        Intent intent = getIntent() ;
        String getId = intent.getStringExtra("goodsManagerId");
        int gId = Integer.parseInt(getId);
        presenter.showGoodsMessage(gId);

        Goods goods = presenter.getGoodsById(gId);
        if (goods.getState().equals("上架中")){
            updateBtn.setText("下架");
        } else if (goods.getState().equals("已下架")) {
            updateBtn.setText("上架");
        }

        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goods.getState().equals("上架中")){
                    new AlertDialog.Builder(GoodsManager.this)
                            .setMessage("确定下架吗？")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            presenter.updateGoodsByIdAndState(gId , "已下架");
                                            Goods goods1 = presenter.getGoodsById(gId);
                                            if (goods1.getState().equals("已下架")){
                                                Toast.makeText(GoodsManager.this, "下架成功", Toast.LENGTH_SHORT).show();
                                                goods_state.setText("已下架");
                                            }
                                        }
                                    })
                                            .setNegativeButton("取消",null)
                                                    .create().show();

                } else if (goods.getState().equals("已下架")) {
                    new AlertDialog.Builder(GoodsManager.this)
                            .setMessage("确定上架吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    presenter.updateGoodsByIdAndState(gId , "上架中");
                                    Goods goods1 = presenter.getGoodsById(gId);
                                    if (goods1.getState().equals("上架中")){
                                        Toast.makeText(GoodsManager.this, "上架成功", Toast.LENGTH_SHORT).show();
                                        goods_state.setText("上架中");
                                    }
                                }
                            })
                            .setNegativeButton("取消",null)
                            .create().show();

                }
            }
        });

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(GoodsManager.this)
                        .setMessage("确定删除该货品吗？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        presenter.updateGoodsByIdAndState(gId,"已删除");
                                        Goods goods = presenter.getGoodsById(gId);
                                        if (goods.getState().equals("已删除")){
                                            Toast.makeText(GoodsManager.this, "商品删除成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        }
                                    }
                                })
                                        .setNegativeButton("取消",null)
                                                .create()
                                                        .show();

            }
        });

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
    @Override
    public void showGoodsMessage(String imgTitle , double price , String unit ,
                                 String goodsName , String address , String freight ,
                                 String goodsText , String imgList , String state) {
        Bitmap bitmap = stringPathToBitmap(imgTitle);
        if (bitmap != null){ // 设置顶部图片
            titlePhoto.setImageBitmap(bitmap);
        }else {
            titlePhoto.setImageResource(R.drawable.add_photo);
        }
        String goodsPrice = String.valueOf(price);
        goods_price.setText(goodsPrice);
        goods_unit.setText(unit);
        goods_state.setText(state);
        goods_name.setText(goodsName);
        goods_local.setText(address);
        goods_logistics.setText(freight);
        goods_details.setText(goodsText);
        imageList.clear();
        String[] imagePath = convertJsonToArray(imgList);
        for (String img : imagePath){
            imageList.add(img);
        }
        if (imageList != null){
            imgAdapter();
            list_photo.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            int size = imageList.size();
            ViewGroup.LayoutParams layoutParams = list_photo.getLayoutParams() ;
            layoutParams.height = 615 * size ;
            list_photo.setLayoutParams(layoutParams);
        }
    }

    public Bitmap stringPathToBitmap(String imagePath) {
        try {
            // 使用BitmapFactory.decodeFile方法将图片路径转换为Bitmap对象
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            if (bitmap != null) {
                return bitmap;
            } else {
                // 图片加载失败处理
                // Log.e("ImageLoadError", "Failed to load image from path: " + imagePath);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return null;
        }
    }


    private static  String[] convertJsonToArray(String jsonString){
        String[] imgPathArray = null ;
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            imgPathArray = new String[jsonArray.length()] ;
            for (int i = 0 ; i < jsonArray.length() ; i++){
                imgPathArray[i] = jsonArray.getString(i) ;
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return imgPathArray ;
    }

    private void imgAdapter(){
        adapter = new ArrayAdapter<String>(this , R.layout.goods_img_list_item , R.id.b1 , imageList){
            public View getView(int position , View converView , ViewGroup parents){
                View view = super.getView(position, converView, parents);
                TextView textView = view.findViewById(R.id.b1);
                ImageView imageView = view.findViewById(R.id.goods_message_item);
                String imgPath = getItem(position);
                Glide.with(GoodsManager.this)
                        .load(imgPath)
                        .into(imageView);
                return view ;
            }


        };
    }

    protected void initView(){
        deleteBtn = findViewById(R.id.goods_manager_deleteGoods);
        updateBtn = findViewById(R.id.goods_manager_update_state);
        backBtn = findViewById(R.id.goods_manager_back);
        titlePhoto = findViewById(R.id.goods_manager_title_photo_show);
        goods_price = findViewById(R.id.goods_manager_show_price_goods);
        goods_unit = findViewById(R.id.goods_manager_show_unit_goods);
        goods_state = findViewById(R.id.goods_manager_show_state);
        goods_name = findViewById(R.id.goods_manager_show_goods_name);
        goods_local = findViewById(R.id.goods_manager_show_local);
        goods_logistics = findViewById(R.id.goods_manager_show_logistics);
        goods_details = findViewById(R.id.goods_manager_show_details);
        list_photo = findViewById(R.id.goods_manager_show_photos);
    }

}
